<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>4_getSnapshotBeforeUpdate的使用场景</title>
</head>

<style>
  .list {
    width: 300px;
    height: 150px;
    margin: 0;
    padding: 10px 20px;
    box-sizing: border-box;
    overflow: auto;
    background-color: aqua;
  }
  .news {
    height: 30px;
    margin: 0 auto;
    padding: 0;
    list-style: none;
  }
</style>

<body>
  <div id="test"></div>
  
  <script src="../js/react.development.js"></script>
  <script src="../js/react-dom.development.js"></script>
  <!-- Don't use this in production: -->
  <script src="../js/babel.min.js"></script>
  <!-- 引入prop-types.js  用于对组件标签属性进行限制 -->

  <script type="text/babel">
    class NewList extends React.Component {
      /* 
      1.初始化阶段：由ReactDOM.render()触发---初次渲染
        constructor()
        static getDerivedStateFromProps
        render()
        componentDidMount()   ====> 常用
            一般在这个钩子中做一些初始化的事，例如：开启定时器、发送网络请求、订阅消息

      2.更新阶段：由组件内部this.setState()或父组件重新render触发
        static getDerivedStateFromProps
        shouldComponentUpdate()
        render()   ====> 必须使用的一个
        getSnapshotBeforeUpdate
        componentDidUpdate()

      3.卸载组件：由ReactDOM.unmountComponentAtNode()触发
        componentWillUnmount()   ====> 常用
              一般在这个钩子中做一些收尾的事，例如：关闭定时器、取消订阅消息
      */
      state = {newsArr: []}

      componentDidMount() {
        setInterval(() => {
          const {newsArr} = this.state
          let news = "新闻" + (newsArr.length + 1)

          this.setState({
            newsArr: [news, ...newsArr]
          })

        }, 1000)
      }

      render(h) {
        const {newsArr} = this.state

        return (
          <ul className="list" ref="list">
            {
              newsArr.map((n, index) => {
                return <div className='news' key={index}>{n}</div>
              })
            }
          </ul>
        )
      }

      getSnapshotBeforeUpdate(prevProps) {
        return this.refs.list.scrollHeight
      }

      componentDidUpdate(prevProps, prevState, height) {
        this.refs.list.scrollTop += this.refs.list.scrollHeight - height
      }
    }

    ReactDOM.render(<NewList/>, document.getElementById("test"))
  </script>
</body>
</html>